package com.tom.imooc.staticdatasource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
public class JdbcUtil {

    private static final String userDb = "test_user";
    private static final String orderDb = "test_order";

    private static final Map<String, Connection> targetDataSource = new ConcurrentHashMap<>(2);

    static {
        Arrays.asList(userDb, orderDb).forEach(JdbcUtil::init);
    }

    private static void init(String db) {
        if (targetDataSource.get(db) == null) { //这里使用双重检验锁
            synchronized (JdbcUtil.class) {
                if (targetDataSource.get(db) == null) {
                    try {
                        Class.forName("com.mysql.cj.jdbc.Driver");
                        Connection connection = DriverManager.getConnection(String.format("jdbc:mysql://localhost:3306/%s?characterEncoding=utf8", db), "root", "123456");
                        targetDataSource.put(db, connection);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void executeSql(String sql, String arg) {
        String currentDb = DataSourceContext.getCurrentDb();
        Connection connection = targetDataSource.get(currentDb);
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setString(1, arg);
            preparedStatement.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
